package com.dtkavin.zk;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * Programmer : John Zn
 * Date : 2016/4/21 0021
 * Time : 13:15
 * Discribtion : 创建对某个path的监听，并获取子节点信息
 */
public class TestClient {
    private ZooKeeper zk;
    private volatile List<String> serverList;
    private String path = "/brokers";

    public void updateServerList() throws Exception {
        ArrayList<String> newServers = new ArrayList<String>();
        List<String> children = zk.getChildren(path, true);//是否对子节点进行监听
        for (String child : children) {
            byte[] data = zk.getData(path + "/" + child, false, new Stat());
            if(data!=null){

                newServers.add(new String(data, "utf-8"));
            }
        }
        serverList = newServers;
        System.out.println("server list updated :" + serverList);
    }


    public void connectZK() throws Exception {

        zk = new ZooKeeper("192.168.98.72:2181", 5000, new Watcher() {

            //            @Override
            public void process(WatchedEvent event) {

                if (event.getType() == EventType.NodeChildrenChanged && path.equals(event.getPath())) {

                    try {
                        updateServerList();
                    } catch (Exception e) {

                        e.printStackTrace();
                    }
                }

            }
        });

        updateServerList();

    }

    public static void main(String[] args) throws Exception {
        TestClient testClient = new TestClient();
        testClient.connectZK();
        Thread.sleep(Long.MAX_VALUE);
    }

}
